package com.meida.module.order.provider.service.impl;

import com.meida.common.constants.CommonConstants;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.utils.ApiAssert;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.module.order.client.entity.OrderDetails;
import com.meida.module.order.client.entity.OrderInfo;
import com.meida.module.order.provider.mapper.OrderDetailsMapper;
import com.meida.module.order.provider.service.OrderDetailsService;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.module.order.provider.service.OrderEvaluateService;
import com.meida.module.order.provider.service.OrderInfoService;
import com.meida.module.order.provider.service.OrderLogisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 订单明细表  实现类
 *
 * @author flyme
 * @date 2019-11-27
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderDetailsServiceImpl extends BaseServiceImpl<OrderDetailsMapper, OrderDetails> implements OrderDetailsService {

    @Autowired
    private OrderLogisticsService logisticsService;

    @Autowired
    private OrderEvaluateService evaluateService;

    @Autowired
    private OrderInfoService infoService;


    /**
     * 查询订单列表中商品明细
     *
     * @param orderId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<EntityMap> listByOrderIdForList(Long orderId, Integer parentOrder) {
        CriteriaQuery<OrderDetails> cq = new CriteriaQuery(OrderDetails.class);
        cq.select(OrderDetails.class, "*");
        cq.select("shop.shopName", "shop.companyId");
        if (parentOrder.equals(CommonConstants.ENABLED)) {
            //母单匹配父ID
            cq.eq(OrderDetails.class, "parentOrderId", orderId);
        } else {
            cq.eq(OrderDetails.class, "orderId", orderId);
        }
        cq.createJoin("com.meida.module.product.client.entity.ProdShop");
        return selectEntityMap(cq);
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforeListEntityMap(CriteriaQuery<OrderDetails> cq, OrderDetails orderDetails, EntityMap requestMap) {
        cq.select(OrderDetails.class, "*");
        cq.eq(OrderDetails.class, "orderId", orderDetails.getOrderId());
        return ResultBody.ok();
    }


    /**
     * 查询订单明细
     *
     * @param orderDetailsId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public EntityMap findByOrderDetailsId(Long orderDetailsId) {
        CriteriaQuery<OrderDetails> cq = new CriteriaQuery(OrderDetails.class);
        cq.select(OrderDetails.class, "*");
        cq.select("shop.shopName", "shop.companyId");
        cq.eq(OrderDetails.class, "orderDetailsId", orderDetailsId);
        cq.createJoin("com.meida.module.product.client.entity.ProdShop");
        return findOne(cq);
    }


    /**
     * 统计订单中店铺数量
     *
     * @param orderId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public Integer coutShopIdCount(Long orderId) {
        CriteriaQuery<OrderDetails> cq = new CriteriaQuery(OrderDetails.class);
        cq.select("COUNT(distinct shopId)");
        cq.eq(true, "orderId", orderId).or().eq(true, "parentOrderId", orderId);
        return getObj(cq, e -> Integer.parseInt(e.toString()));
    }


    /**
     * 查询营销商品是否已购买
     *
     * @param marketingId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public Integer checkMarketingProduct(Long marketingId, Long userId) {
        CriteriaQuery<OrderDetails> cq = new CriteriaQuery(OrderDetails.class);
        cq.eq(true, "marketingId", marketingId);
        cq.eq(true, "userId", userId);
        return count(cq);
    }

    /**
     * 查询订单中店铺ID
     *
     * @param orderId
     * @return
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<Long> selectShopId(Long orderId, Integer parentOrder) {
        CriteriaQuery<OrderDetails> cq = new CriteriaQuery(OrderDetails.class);
        cq.select("shopId");
        if (parentOrder.equals(CommonConstants.ENABLED)) {
            cq.eq(true, "parentOrderId", orderId);
        } else {
            cq.eq(true, "orderId", orderId);
        }
        cq.groupBy("shopId");
        return listObjs(cq, e -> Long.parseLong(e.toString()));
    }

    /**
     * 查询订单详情中的商品明细
     *
     * @param orderId
     * @param parentOrder
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<EntityMap> listByOrderIdForDetails(Long orderId, Integer parentOrder) {
        List<Long> shopIds = selectShopId(orderId, parentOrder);
        List<EntityMap> allList = new ArrayList<>();
        List<EntityMap> allProductList = listByOrderIdForList(orderId, parentOrder);
        for (Long shopId : shopIds) {
            List<EntityMap> productList = new ArrayList<>();
            EntityMap shopDetails = new EntityMap();
            BigDecimal totalAmount = new BigDecimal("0");
            Long subOrderId = null;
            Integer evaluatedCount = 0;
            for (EntityMap product : allProductList) {
                Long id = product.getLong("shopId");
                if (shopId.equals(id)) {
                    subOrderId = product.getLong("orderId");
                    OrderInfo orderInfo = infoService.getById(subOrderId);
                    shopDetails.put("couponAmount", orderInfo.getCouponAmount());
                    shopDetails.put("freightAmount", orderInfo.getFreightAmount());
                    shopDetails.put("productCount", orderInfo.getProductCount());
                    shopDetails.put("payAmount", orderInfo.getPayAmount());
                    shopDetails.put("leaveMsg", orderInfo.getLeaveMsg());
                    String shopName = product.get("shopName");
                    Integer evaluatedState = product.getInt("evaluatedState", 0);
                    BigDecimal productAmount = product.getBigDecimal("productAmount");
                    shopDetails.putIfAbsent("shopName", shopName);
                    totalAmount = totalAmount.add(productAmount);
                    evaluatedCount += evaluatedState;
                    productList.add(product);
                }
            }

            shopDetails.put("evaluatedCount", evaluatedCount);

            shopDetails.put("totalAmount", totalAmount);
            shopDetails.put("productList", productList);
            allList.add(shopDetails);
        }
        return allList;
    }

    /**
     * 查询订单明细评价信息
     *
     * @param params
     * @return
     */
    @Override
    public ResultBody getCommentInfo(Map params) {
        CriteriaQuery<OrderDetails> cq = new CriteriaQuery(params, OrderDetails.class);
        OrderDetails request = cq.getEntity(OrderDetails.class);
        Long orderDetailsId = request.getOrderDetailsId();
        ApiAssert.isNotEmpty("订单明细ID不能为空", orderDetailsId);
        OrderDetails orderDetails = getById(orderDetailsId);
        cq.select(OrderDetails.class, "*");
        EntityMap entityMap = findOne(cq);
        OrderInfo orderInfo = infoService.getById(orderDetails.getOrderId());
        //物流信息
        EntityMap orderLogistics = logisticsService.findByOrderId(orderDetails.getOrderId());

        Integer logisticsScore = 0;
        if (FlymeUtils.isNotEmpty(orderLogistics)) {
            //物流评分
            logisticsScore = orderLogistics.getInt("logisticsScore", 0);
        }

        entityMap.put("logisticsScore", logisticsScore);
        //店铺评分
        entityMap.put("shopScore", orderInfo.getShopScore());


        //订单评价
        EntityMap orderEvaluate = evaluateService.findByOrderDetailsId(orderDetailsId);
        Integer evaluateScore = 0;
        Integer describeScore = 0;
        if (FlymeUtils.isNotEmpty(orderEvaluate)) {
            describeScore = orderEvaluate.getInt("describeScore", describeScore);
            evaluateScore = orderEvaluate.getInt("evaluateScore", 0);
        }
        //商品评分
        entityMap.put("evaluateScore", evaluateScore);
        //描述评分
        entityMap.put("describeScore", describeScore);
        return ResultBody.ok(entityMap);
    }

    /**
     * 更新评价状态
     *
     * @param orderDetailsId
     * @param evaluatedState
     */
    @Override
    public void setEvaluatedState(Long orderDetailsId, Integer evaluatedState) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "evaluatedState", evaluatedState);
        cu.eq(true, "orderDetailsId", orderDetailsId);
        update(cu);
    }

    /**
     * 更新售后状态
     *
     * @param orderDetailsId
     * @param afterSaleState
     */
    @Override
    public void setAfterSaleState(Long orderDetailsId, Integer afterSaleState) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "afterSaleState", afterSaleState);
        cu.eq(true, "orderDetailsId", orderDetailsId);
        update(cu);
    }


}
